package com.mycompany.myapp.repository;

import com.mycompany.myapp.domain.SUser;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

import static com.mycompany.myapp.repository.UserRepository.USERS_BY_LOGIN_CACHE;


/**
 * Spring Data  repository for the SUser entity.
 */
@SuppressWarnings("unused")
@Repository
public interface SUserRepository extends JpaRepository<SUser, Long> {

    String USERS_BY_PHONE_CACHE = "usersByPhone";

    String USERS_BY_EMAIL_CACHE = "usersByEmail";

    /**
     * 根据账号查询用户
     *
     * @param username
     * @return
     */
    Optional<SUser> findOneByUsername(String username);

    Optional<SUser> findOneByPhone(String phone);

    Optional<SUser> findOneByEmailIgnoreCase(String email);


    @EntityGraph(attributePaths = "authorities")
    @Cacheable(cacheNames = USERS_BY_PHONE_CACHE)
    Optional<SUser> findOneWithAuthoritiesByPhone(String phone);

    @EntityGraph(attributePaths = "authorities")
    @Cacheable(cacheNames = USERS_BY_EMAIL_CACHE)
    Optional<SUser> findOneWithAuthoritiesByEmail(String email);

    @EntityGraph(attributePaths = "authorities")
    List<SUser> findAll();

    SUser findOneByEmail(String Email);

    SUser findByUsername(String username);

    @Query("select su from SUser su where su.username = ?1 or su.email = ?1 and su.password = ?2")
    SUser findByUsernameAndPassword(String username, String password);

    @Modifying
    @Query("update SUser su set su.password = ?1  where su.id = ?2")
    int changePasswordById(String password, Long id);

    @EntityGraph(attributePaths = "authorities")
    Page<SUser> findSUsersByUsernameLike(String username, Pageable pageable);

    @Modifying
    @Query("update SUser su set su.isActive = ?2  where su.id = ?1")
    int updateState(long userId, boolean isActive);
}
